/*******************************************************************************
*  file    : qloggerrollingfileappender.cpp
*  created : 15.11.2011
*  author  : Slyshyk Oleksiy (alex312@meta.ua)
*******************************************************************************/

#include <QFile>
#include <QFileInfo>
#include <QDateTime>
#include <QDebug>
#include "qloggerrollingfileappender.hpp"

QLoggerRollingFileAppender::QLoggerRollingFileAppender(int level,
                                                       const QString &filename,
                                                       const QString &format,
                                                       int max_size,
                                                       const QString& time_format)
    :QLoggerFileAppender(level,filename,format,time_format),
     _max_file_size(max_size)
{

}

void QLoggerRollingFileAppender::rollFile()
{
    QString file_name;
    QFile file(_filename);

    if(file.size() > _max_file_size)
        {
            QFileInfo fi(_filename);
            file_name = QString("%1/%2[%3].bak")
                        .arg(fi.absolutePath())
                        .arg(fi.baseName())
                        .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss"));

            if( ! file.rename(file_name))
                 qDebug()<<"Rename error - "<<file.errorString();
        }
}

void QLoggerRollingFileAppender::write (const QLoggerEvent &event)
{
    QMutexLocker lock(&mutex);

    rollFile();

    QFile file(_filename);
    if (file.open(QFile::WriteOnly | QFile::Append))
        {
            QTextStream out(&file);
            out.setCodec(_codec);
            streamWrite(out, event);
            file.close();
        }
}
